package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.Appointment;
import com.docking.heylo.dao.entity.AppointmentExample;
import com.docking.heylo.dao.entity.Evaluate;
import com.docking.heylo.dao.entity.PersonalInformation;
import com.docking.heylo.dao.mapper.AppointmentMapper;
import com.docking.heylo.dao.mapper.EvaluateMapper;
import com.docking.heylo.dao.mapper.PersonalInformationMapper;
import com.docking.heylo.enums.EProfession;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.service.IAppointmentService;
import com.docking.heylo.service.IEvaluateService;
import com.docking.heylo.utils.HeyloMessageSource;
import com.docking.heylo.web.dto.EvaluteListDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class EvaluateServiceImpl implements IEvaluateService {

    @Resource
    private EvaluateMapper evaluateMapper;

    @Resource
    private AppointmentMapper appointmentMapper;

    @Autowired
    private HeyloMessageSource messageSource;

    @Resource
    private PersonalInformationMapper personalInformationMapper;

    @Autowired
    private IAppointmentService appointmentService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class, noRollbackFor = GeneralException.class, propagation = Propagation.SUPPORTS)
    public void pushEvaluate(Evaluate evaluate) {
        Appointment appointment = appointmentMapper.selectByPrimaryKey(evaluate.getAppointmentId());

        if(ThreadContext.authorize.get().getUser().getType() == EProfession.model.getValue()){
            mPushEvaluate(evaluate, appointment);
        }else{
            pPushEvaluate(evaluate, appointment);
        }
    }

    @Override
    public PageInfo<Map<String, Object>> evaluateForUser(EvaluteListDto evaluteListDto) {
        PageHelper.startPage(evaluteListDto.getPageNumber(),evaluteListDto.getSize());
        PageHelper.orderBy("crt_at desc");

        return new PageInfo<>(evaluateMapper.evaluateForUser(evaluteListDto.getRevieweeId()));
    }

    /***
     * 模特评论
     */
    public void mPushEvaluate(Evaluate evaluate, Appointment appointment){
        if(1 == appointment.getmEva()){
            throw new GeneralException(messageSource.getMessage("comment.repeat"));
        }

        evaluate.setRevieweeId(appointment.getPhotographerId());
        evaluate.setPublisherId(ThreadContext.informationId());
        evaluate.setCrtAt(new Date());
        evaluateMapper.insertSelective(evaluate);

        AppointmentExample example = new AppointmentExample();
        AppointmentExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(appointment.getId());
        criteria.andMEvaEqualTo((byte) 0);
        int row = appointmentMapper.updateByExampleSelective(new Appointment(){{
            setmScore(evaluate.getScore());
            setmEva((byte) 1);
        }}, example);
        if(row != 1){
            throw new GeneralException(messageSource.getMessage("comment.repeat"));
        }

        // 摄影师好评率
        PersonalInformation pi = personalInformationMapper.selectByPrimaryKey(appointment.getPhotographerId());
        pi.setPraise((double) calculationStar(pi.getPraise().intValue(), evaluate.getScore().intValue()));
        personalInformationMapper.updateByPrimaryKeySelective(new PersonalInformation(){{
            setId(pi.getId());
            setPraise(pi.getPraise());
        }});
        
        // 如果订单已经完成则不用处理
        appointmentService.end(appointment);

    }


    /***
     * 摄影师评论
     */
    public void pPushEvaluate(Evaluate evaluate, Appointment appointment){
        if(1 == appointment.getpEva()){
            throw new GeneralException(messageSource.getMessage("comment.repeat"));
        }
        evaluate.setRevieweeId(appointment.getUserId());
        evaluate.setPublisherId(ThreadContext.informationId());
        evaluate.setCrtAt(new Date());
        evaluateMapper.insertSelective(evaluate);

        appointmentMapper.updateByPrimaryKeySelective(new Appointment(){{
            setId(appointment.getId());
            setpScore(evaluate.getScore());
            setpEva((byte) 1);
        }});

        // 模特
        PersonalInformation pi = personalInformationMapper.selectByPrimaryKey(appointment.getUserId());
        pi.setPraise((double) calculationStar(pi.getPraise().intValue(), evaluate.getScore().intValue()));
        personalInformationMapper.updateByPrimaryKeySelective(new PersonalInformation(){{
            setId(pi.getId());
            setPraise(pi.getPraise());
        }});
    }


    public final static BigDecimal b100 = new BigDecimal(100);
    public final static BigDecimal b2   = new BigDecimal(2);

    /***
     * 计算好评率
     *
     * @param nowStar       现在评分
     * @param star          评分
     * @return
     */
    public int calculationStar(int nowStar, int star){
        BigDecimal d = new BigDecimal(star).divide(new BigDecimal(5),2,BigDecimal.ROUND_DOWN).multiply(b100);
        return nowStar > 0 ? d.add(new BigDecimal(nowStar)).divide(b2,2,BigDecimal.ROUND_DOWN).intValue() : d.intValue();
    }




}
